package net.diaowen.dwsurvey.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.diaowen.common.base.dao.UserDao;
import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.common.service.BaseServiceImpl;
import net.diaowen.common.utils.SystemUtils;
import net.diaowen.common.utils.excel.ReadExcelUtil;
import net.diaowen.common.utils.security.DigestUtils;
import net.diaowen.dwsurvey.service.GroupManager;
import net.diaowen.dwsurvey.service.UserManager;



/**
 * 用户管理
 * @author keyuan(keyuan258@gmail.com)
 *
 * https://github.com/wkeyuan/DWSurvey
 * http://dwsurvey.net
 */
@Service
public class UserManagerImpl extends BaseServiceImpl<User, String> implements UserManager {
	
	@Autowired
	private AccountManager accountManager;

	@Autowired
	private GroupManager groupManager;
	
	@Autowired
	private UserDao userDao;

	@Override
	public void setBaseDao() {
		this.baseDao=userDao;
	}

	@Override
	public void adminSave(User entity, String[] userRoleIds) throws Exception {
		if(entity!=null){

			String pwd=entity.getPwd();
			if(pwd!=null && !"".equals(pwd)){
				//加点盐
//				String salt=RandomUtils.randomWordNum(5);
				String shaPassword = DigestUtils.sha1Hex(pwd);
				entity.setShaPassword(shaPassword);
//				entity.setSalt(salt);
			}
			try {
				// 增加orgId
				User curUser = accountManager.getCurUser();
				entity.setOrgId(curUser.getOrgId());
				entity.setLoginName(curUser.getOrgId() + "_" + entity.getStudentId());
				save(entity);
				getBaseDao().flush();
	
			} catch (Exception e) {
				 e.printStackTrace();
				throw new Exception(e);
				
			}
			
		}
	}

	public Page<User> findPage(Page<User> page, User entity) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		Integer status = entity.getStatus();
		String studentId = entity.getStudentId();
		System.out.println("status:"+status);
		if(status!=null && !"".equals(status)){
			criterions.add(Restrictions.eq("status", status));
		}
		if(studentId!=null && !"".equals(studentId)){
			criterions.add(Restrictions.like("studentId", "%"+studentId+"%"));
		}
		criterions.add(Restrictions.disjunction().add(Restrictions.eq("visibility", 1)).add(Restrictions.isNull("visibility")));
		
		User curUser = accountManager.getCurUser();
		//如果是超级管理员则不加入机构ID查询，其余管理员加入机构ID
		if (curUser.getSystemRole() == 8) {
			//
		} else {
			criterions.add(Restrictions.eq("orgId", curUser.getOrgId()));
			System.out.println("用户管理curUser.getOrgId() = " + curUser.getOrgId());
		}
		page.setOrderBy("createTime");
		page.setOrderDir("desc");
		return super.findPageByCri(page, criterions);
	}

	/**
	 * 禁用账号
	 */
	@Transactional
	@Override
	public void disUser(String id) {
		User user=get(id);
		int status=user.getStatus();
		if(status==0){
			user.setStatus(1);
		}else{
			user.setStatus(0);
		}
		save(user);
	}

	////物理删除一了百了
	/**
	 * 禁用账号
	 */
/*	@Transactional
	@Override
	public void delete(String id) {
		User user=get(id);
		user.setVisibility(0);
		save(user);
	}*/

	@Override
	public User findNameUn(String id, String loginName) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("loginName", loginName));
		if(id!=null && !"".equals(id)){
			criterions.add(Restrictions.ne("id", id));
		}
		return userDao.findFirst(criterions);
	}
	
	@Override
	public User findLoginName(String loginName) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("loginName", loginName));
		return userDao.findFirst(criterions);
	}

	@Override
	public User findOrgStudentId(String orgId, String studentId) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("orgId", orgId));
		criterions.add(Restrictions.eq("studentId", studentId));
		User u = userDao.findFirst(criterions);
		return u;
	}


	@Override
	public User findEmailUn(String id, String email) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("email", email));
		if(id!=null && !"".equals(id)){
			criterions.add(Restrictions.ne("id", id));
		}
		return userDao.findFirst(criterions);
	}

	@Override
	public User findByCode(String code) {
		Criterion criterion=Restrictions.eq("findPwdCode", code);
		return userDao.findFirst(criterion);
	}

	@Override
	public User findByActivationCode(String activationCode) {
		Criterion criterion=Restrictions.eq("activationCode", activationCode);
		return userDao.findFirst(criterion);
	}

	@Override
	public void resetUserGroup(String groupId) {
		userDao.resetUserGroup(groupId);
	}


	@Override
	public Page<User> findPageByKeyword(Page<User> page, String keyword) {
		Criterion cri1=Restrictions.like("name", "%"+keyword+"%");
//		Criterion cri2=Restrictions.like("pinyin", "%"+keyword+"%");
//		Criterion cri3 = Restrictions.or(cri1,cri2);
		return userDao.findPage(page,cri1);
	}

	@SuppressWarnings("deprecation")
	@Override
	public Map<String,Object> doBatchImport(String filepath) {
		HSSFWorkbook workBook;
		List<String> msg = new ArrayList<String>();
		Map<String,Object> map = new HashMap<String,Object>();
		int rowNum = 0;
		int successcnt = 0;
		int effectiveNum = 0;
		workBook = ReadExcelUtil.getWorkBook(filepath);
		HSSFSheet hssfSheet = ReadExcelUtil.getHSSFSheet(workBook,0);
		rowNum = hssfSheet.getPhysicalNumberOfRows();

		//查询当登录用户
		User curUser = null;
		try {
			//开始插入
			 curUser = accountManager.getCurUser();
		}catch (Exception e){
			e.getMessage();
			msg.add("查询当前用户失败"+ e.getMessage());
			map.put("msg", msg);
			map.put("rowNum", effectiveNum);
			map.put("successcnt", successcnt);
			return map;
		}
		
		for(int j = 1; j < rowNum; j++) {
			try {
			HSSFRow row = hssfSheet.getRow(j);
			//清一色全部换成String 如果格式不对直接跳过
			try {
				if(row.getCell(0) == null) {
					row.createCell(0).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(0).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(1) == null) {
					row.createCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(2) == null) {
					row.createCell(2).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(2).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(3) == null) {
					row.createCell(3).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(3).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(4) == null) {
					row.createCell(4).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(4).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(5) == null) {
					row.createCell(5).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(5).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(6) == null) {
					row.createCell(6).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(6).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(7) == null) {
					row.createCell(7).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(7).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(8) == null) {
					row.createCell(8).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(8).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
				if(row.getCell(9) == null) {
					row.createCell(9).setCellType(XSSFCell.CELL_TYPE_STRING);
				} else {
					row.getCell(9).setCellType(XSSFCell.CELL_TYPE_STRING);
				}
			}catch(Exception e ){
				continue;
			}
			effectiveNum = effectiveNum + 1;
			
			//开始验证excle格式
			String ex_phone = row.getCell(0).getStringCellValue();
			String ex_email = row.getCell(1).getStringCellValue();
			String ex_name = row.getCell(2).getStringCellValue();
			String ex_school = row.getCell(3).getStringCellValue();
			String ex_college = row.getCell(4).getStringCellValue();
			String ex_major = row.getCell(5).getStringCellValue();
			String ex_studengId = row.getCell(6).getStringCellValue();
			//第七列特殊，做日期格式化
			String ex_entime = SystemUtils.getCellValueDate(row.getCell(7));
			String ex_sex = row.getCell(8).getStringCellValue();
			String ex_province = row.getCell(9).getStringCellValue();
			//TODO 每一列都循环验证
			
			
			User user = new User();
			user.setCellphone(ex_phone);
			user.setEmail(ex_email);
			user.setPwd(ex_email);
			user.setName(ex_name);
			user.setSchool(ex_school);
			user.setMajor(ex_major);
			user.setCollege(ex_college);
			user.setStudentId(ex_studengId);
			
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date edate = dateFormat.parse(ex_entime);
			user.setEnrollmentTime(edate);
			user.setEnrollmentTimeStr(ex_entime);
			if(ex_sex.equals("男")){
				user.setSex(0);
			} else {
				user.setSex(1);
			}
			user.setProvince(ex_province);
			
			//判断用户是否已存在
			User userTemp = findOrgStudentId(curUser.getOrgId(),user.getStudentId());
			if (userTemp != null) {
				userTemp.setCellphone(user.getCellphone());
				userTemp.setEmail(user.getEmail());
				//userTemp.setPwd(user.getPwd());
				userTemp.setName(user.getName());
				userTemp.setSchool(user.getSchool());
				userTemp.setMajor(user.getMajor());
				userTemp.setCollege(user.getCollege());
				userTemp.setStudentId(user.getStudentId());
				userTemp.setEnrollmentTime(user.getEnrollmentTime());
				userTemp.setEnrollmentTimeStr(user.getEnrollmentTimeStr());
				userTemp.setSex(user.getSex());
				userTemp.setProvince(user.getProvince());
				adminSave(userTemp,null);
				msg.add("第" +j + "行，系统中已经存在此用户,本次已更新");
				
			} else {
				adminSave(user, null);
			}
		
			successcnt = successcnt + 1;
			
			}catch (Exception e) {
				msg.add("第" +j + "行，插入失败,原因："+e.getMessage());
					e.printStackTrace();
				}

}
		
		map.put("msg", msg);
		map.put("rowNum", effectiveNum);
		map.put("successcnt", successcnt);
		
		return map;
	}


	@Override
	public Page<User> findPage(Page<User> page, User entity, String groupId) {
		
		String hql = "select u from User u,UserGroup tug where u.id = tug.userId and tug.usergroupId = ?";
		Integer status = entity.getStatus();
		String studentId = entity.getStudentId();
		if(status!=null && !"".equals(status)){
			hql = hql + "and u.status =" + status;
		}
		if(studentId!=null && !"".equals(studentId)){
			hql = hql + "and u.studentId like '%"+studentId+"%'";
		}
		//如果是超级系统管理员，则去小组表取orgId
		User curUser = accountManager.getCurUser();
		String orgId = "";
		if(curUser.getSystemRole() == 8) {
			orgId = groupManager.findOne(groupId).getOrgId();
		} else {
			orgId = curUser.getOrgId();
		}
		hql = hql + "and u.orgId =" + orgId;
		//加一个排序项，与user画面一致
		hql = hql + "order by u.createTime desc";		
		return  userDao.findPage(page,hql, groupId);
	}
	
	
	@Override
	public Page<User> findUserSelectPage(Page<User> page, User entity, String groupId) {
		
		String hql = "select u from User u where u.id not in (select tug.userId from UserGroup tug where tug.usergroupId = ?)";
		Integer status = entity.getStatus();
		String studentId = entity.getStudentId();
		if(status!=null && !"".equals(status)){
			hql = hql + "and u.status =" + status;
		}
		if(studentId!=null && !"".equals(studentId)){
			hql = hql + "and u.studentId like '%"+studentId+"%'";
		}
		//如果是超级系统管理员，则去小组表取orgId
		User curUser = accountManager.getCurUser();
		String orgId = "";
		if(curUser.getSystemRole() == 8) {
			orgId = groupManager.findOne(groupId).getOrgId();
		} else {
			orgId = curUser.getOrgId();
		}
		hql = hql + "and u.orgId =" + orgId;
		return  userDao.findPage(page,hql, groupId);
	}

	@Override
	public void adminSaveWithOrgId(User entity, String orgId) throws Exception {
		if(entity!=null){

			String pwd=entity.getPwd();
			if(pwd!=null && !"".equals(pwd)){
				String shaPassword = DigestUtils.sha1Hex(pwd);
				entity.setShaPassword(shaPassword);
			}
			try {
				entity.setOrgId(orgId);
				entity.setLoginName(orgId + "_" + entity.getStudentId());
				save(entity);
				getBaseDao().flush();
	
			} catch (Exception e) {
				 e.printStackTrace();
				throw new Exception(e);
				
			}
			
		}
		
	}

	@Override
	public List<User> findUserByOrgId(String orgId) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("orgId", orgId));
		criterions.add(Restrictions.eq("systemRole", 9));
		return userDao.findAll(criterions);
	}

	@Override
	public List<User> selectorgid(String id) throws Exception {
		return userDao.selectorgid(id);
	}

//	删除用户
	@Override
	public int deleteuser(String email, String name) throws Exception {
		return userDao.deleteuser(email,name);
	}

}
